import {UPLOADINFO, UPLOADTYPE, BASEURL, CHUNKSIZE} from './cofig'
import axios from "axios";

;((dcu) => {
    let uploadBtn = dcu.querySelector('#uploadBtn');
    let uploadProgress = dcu.querySelector('#uploadProgress');
    let fileUpload = dcu.querySelector('#fileUpload');
    let uploadInfo = dcu.querySelector('#uploadInfo');


    let uploadSize = 0 //用于保存当前上传了多少

    const init = () => {
        bindEvent()
    }

    function bindEvent() {
        uploadBtn.addEventListener('click', uploadHandler, false)
    }

    async function uploadHandler() {
        // let file = fileUpload.files[0]
        const {files: [file]} = fileUpload
        console.log(file)
        if (!file) { // 没有文件
            uploadInfo.innerText = UPLOADINFO['NO_INFO']
            return;
        }
        if (!UPLOADTYPE[file.type]) { // 规定上传的类型
            uploadInfo.innerText = UPLOADINFO['TYPE_INFO']
            return
        }

        const {type, name, size} = file
        let fileName = new Date().getTime() + '_' + name
        uploadProgress.max = size
        uploadInfo.innerText = uploadInfo.innerText = UPLOADINFO['UPLOAD_LOADING']
        let res; // 返回成功的结果
        while (uploadSize < size) { // 规定的文件小于要上传的文件就切片处理
            let chunk = file.slice(uploadSize, uploadSize + CHUNKSIZE)
            const formData = createFormData({
                name: name,
                type: type,
                fileName: fileName,
                size: size,
                uploadSize: uploadSize,
                file: chunk
            })
            console.log('idwa', formData) // 上传的fromData对象

            try {
                res = await axios.post(BASEURL, formData) // 上传的接口
                console.log('dwa', res)
            } catch (err) {
                uploadInfo.innerText = uploadInfo.innerText = `${UPLOADINFO['UPLOAD_ERROR']} +  ${err}`
                throw err
            }
            // 拼接上传的数据
            uploadSize += chunk.size // 拼接切割的size
            uploadProgress.value = uploadSize // 进度条的zize

        }

        uploadInfo.innerText = uploadInfo.innerText = UPLOADINFO['UPLOAD_SUCCESS']
        // 上传完成创建视频标签
        if(res.data.fileUrl) await createVideo(res.data.fileUrl) // 上传成功创建视频标签
    }

    function createFormData({name, type, fileName, size, uploadSize, file}) {  // 创建formData对象
        let fd = new FormData()
        fd.append('name', name)
        fd.append('type', type)
        fd.append('fileName', fileName)
        fd.append('size', size)
        fd.append('uploadSize', uploadSize)
        fd.append('file', file)
        return fd
    }

    function createVideo (url) { //创建一个视频的标签插入到页面
        console.log(url)
        const eleVideo = document.createElement('video')
        eleVideo.controls = true
        eleVideo.width = '500'
        eleVideo.src = url
        document.body.appendChild(eleVideo)
    }


    init()
})(document);
